import tkinter as tk
from tkinter import ttk, font as tkfont
import colorsys
from PIL import Image, ImageTk, ImageDraw
import math

class RoundedFrame(tk.Frame):
    """圆角框架类"""
    def __init__(self, parent, bg_color='#2C3E50', corner_radius=20, **kwargs):
        super().__init__(parent, **kwargs)
        self.bg_color = bg_color
        self.corner_radius = corner_radius
        self.config(bg=bg_color)
        
        # 创建圆角效果
        self.bind('<Configure>', self._on_configure)
        
    def _on_configure(self, event):
        """处理窗口大小变化"""
        self._create_rounded_rectangle()
    
    def _create_rounded_rectangle(self):
        """创建圆角矩形效果"""
        width = self.winfo_width()
        height = self.winfo_height()
        
        if width > 1 and height > 1:
            # 使用PIL创建圆角矩形
            image = Image.new('RGBA', (width, height), (0, 0, 0, 0))
            draw = ImageDraw.Draw(image)
            
            # 绘制圆角矩形
            self._draw_rounded_rectangle(draw, 0, 0, width-1, height-1, 
                                       self.corner_radius, fill=self.bg_color)
            
            # 转换为PhotoImage
            self.rounded_image = ImageTk.PhotoImage(image)
            
            # 创建标签显示圆角图像
            if hasattr(self, 'bg_label'):
                self.bg_label.destroy()
            
            self.bg_label = tk.Label(self, image=self.rounded_image, bg=self.bg_color)
            self.bg_label.place(x=0, y=0, relwidth=1, relheight=1)
            self.bg_label.lower()
    
    def _draw_rounded_rectangle(self, draw, x1, y1, x2, y2, radius, **kwargs):
        """绘制圆角矩形"""
        points = [
            (x1 + radius, y1),
            (x2 - radius, y1),
            (x2, y1 + radius),
            (x2, y2 - radius),
            (x2 - radius, y2),
            (x1 + radius, y2),
            (x1, y2 - radius),
            (x1, y1 + radius),
        ]
        
        # 绘制直线
        draw.line([(x1 + radius, y1), (x2 - radius, y1)], **kwargs)
        draw.line([(x2, y1 + radius), (x2, y2 - radius)], **kwargs)
        draw.line([(x2 - radius, y2), (x1 + radius, y2)], **kwargs)
        draw.line([(x1, y2 - radius), (x1, y1 + radius)], **kwargs)
        
        # 绘制圆弧
        draw.arc([x1, y1, x1 + 2*radius, y1 + 2*radius], 180, 270, **kwargs)
        draw.arc([x2 - 2*radius, y1, x2, y1 + 2*radius], 270, 360, **kwargs)
        draw.arc([x2 - 2*radius, y2 - 2*radius, x2, y2], 0, 90, **kwargs)
        draw.arc([x1, y2 - 2*radius, x1 + 2*radius, y2], 90, 180, **kwargs)

class GridBackground:
    """网格背景类"""
    def __init__(self, canvas, grid_size=20, grid_color='#34495E', bg_color='#2C3E50'):
        self.canvas = canvas
        self.grid_size = grid_size
        self.grid_color = grid_color
        self.bg_color = bg_color
        self.grid_items = []
        
    def draw_grid(self):
        """绘制网格背景"""
        width = self.canvas.winfo_width()
        height = self.canvas.winfo_height()
        
        # 清除现有网格
        self.clear_grid()
        
        # 绘制垂直线
        for x in range(0, width, self.grid_size):
            line = self.canvas.create_line(x, 0, x, height, 
                                         fill=self.grid_color, width=1)
            self.grid_items.append(line)
        
        # 绘制水平线
        for y in range(0, height, self.grid_size):
            line = self.canvas.create_line(0, y, width, y, 
                                         fill=self.grid_color, width=1)
            self.grid_items.append(line)
    
    def clear_grid(self):
        """清除网格"""
        for item in self.grid_items:
            self.canvas.delete(item)
        self.grid_items.clear()

class StyleManager:
    """样式管理器"""
    def __init__(self):
        self.themes = {
            '经典': {
                'bg_color': '#F5F5DC',
                'text_color': '#2C3E50',
                'highlight_color': '#E74C3C',
                'pinyin_color': '#7F8C8D',
                'accent_color': '#3498DB'
            },
            '水墨': {
                'bg_color': '#F8F8F8',
                'text_color': '#2C3E50',
                'highlight_color': '#C0392B',
                'pinyin_color': '#95A5A6',
                'accent_color': '#34495E'
            },
            '雅致': {
                'bg_color': '#F0F8FF',
                'text_color': '#2C3E50',
                'highlight_color': '#FF6B6B',
                'pinyin_color': '#87CEEB',
                'accent_color': '#4ECDC4'
            },
            '夜间': {
                'bg_color': '#2C3E50',
                'text_color': '#ECF0F1',
                'highlight_color': '#F39C12',
                'pinyin_color': '#BDC3C7',
                'accent_color': '#3498DB'
            }
        }
    
    def get_theme(self, theme_name):
        """获取主题配置"""
        return self.themes.get(theme_name, self.themes['经典'])
    
    def get_available_themes(self):
        """获取可用主题列表"""
        return list(self.themes.keys())

def create_gradient_background(canvas, color1, color2, width, height):
    """创建渐变背景"""
    image = Image.new('RGB', (width, height))
    
    # 简单的渐变算法
    for y in range(height):
        # 计算渐变比例
        ratio = y / height
        
        # 解析颜色
        r1, g1, b1 = tuple(int(color1[i:i+2], 16) for i in (1, 3, 5))
        r2, g2, b2 = tuple(int(color2[i:i+2], 16) for i in (1, 3, 5))
        
        # 插值计算
        r = int(r1 + (r2 - r1) * ratio)
        g = int(g1 + (g2 - g1) * ratio)
        b = int(b1 + (b2 - b1) * ratio)
        
        # 绘制行
        for x in range(width):
            image.putpixel((x, y), (r, g, b))
    
    return ImageTk.PhotoImage(image)

def create_text_shadow(canvas, text_item, offset=2, shadow_color='#000000'):
    """为文本创建阴影效果"""
    # 获取文本位置
    coords = canvas.coords(text_item)
    if not coords:
        return None
    
    x, y = coords[0] + offset, coords[1] + offset
    
    # 获取文本属性
    text = canvas.itemcget(text_item, 'text')
    font = canvas.itemcget(text_item, 'font')
    
    # 创建阴影文本
    shadow = canvas.create_text(x, y, text=text, font=font, 
                               fill=shadow_color, state='disabled')
    
    # 将阴影置于原文本下方
    canvas.tag_lower(shadow, text_item)
    
    return shadow

class EnhancedPoetryDisplay:
    """增强版诗词显示类"""
    def __init__(self, parent, **kwargs):
        self.parent = parent
        self.style_manager = StyleManager()
        self.current_theme = '经典'
        
        # 创建主框架
        self.main_frame = RoundedFrame(parent, bg_color='#F5F5DC', corner_radius=20)
        self.main_frame.pack(fill='both', expand=True, padx=20, pady=20)
        
        # 创建画布用于显示背景效果
        self.canvas = tk.Canvas(self.main_frame, bg='#F5F5DC', 
                               highlightthickness=0, bd=0)
        self.canvas.pack(fill='both', expand=True)
        
        # 网格背景
        self.grid_bg = GridBackground(self.canvas, grid_size=25, 
                                    grid_color='#E8E8E8', bg_color='#F5F5DC')
        
        # 文本显示配置
        self.text_items = []
        self.pinyin_items = []
        self.shadow_items = []
        
        # 绑定窗口大小变化事件
        self.canvas.bind('<Configure>', self._on_canvas_configure)
    
    def _on_canvas_configure(self, event):
        """处理画布大小变化"""
        # 延迟执行以避免频繁重绘
        if hasattr(self, '_configure_after_id'):
            self.canvas.after_cancel(self._configure_after_id)
        
        self._configure_after_id = self.canvas.after(100, self._redraw_background)
    
    def _redraw_background(self):
        """重绘背景"""
        # 更新网格背景
        self.grid_bg.draw_grid()
    
    def apply_theme(self, theme_name):
        """应用主题"""
        self.current_theme = theme_name
        theme = self.style_manager.get_theme(theme_name)
        
        # 更新背景颜色
        self.canvas.config(bg=theme['bg_color'])
        self.main_frame.config(bg_color=theme['bg_color'])
        self.grid_bg.bg_color = theme['bg_color']
        self.grid_bg.grid_color = self._adjust_color_brightness(theme['bg_color'], -30)
        
        # 重绘背景
        self._redraw_background()
    
    def _adjust_color_brightness(self, hex_color, amount):
        """调整颜色亮度"""
        # 简单的亮度调整
        hex_color = hex_color.lstrip('#')
        r, g, b = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4))
        
        r = max(0, min(255, r + amount))
        g = max(0, min(255, g + amount))
        b = max(0, min(255, b + amount))
        
        return f'#{r:02x}{g:02x}{b:02x}'
    
    def display_poetry(self, poetry_data, current_index=0, highlight_color=None):
        """显示诗词内容"""
        # 清除现有内容
        self.clear_display()
        
        if not poetry_data:
            return
        
        theme = self.style_manager.get_theme(self.current_theme)
        if highlight_color is None:
            highlight_color = theme['highlight_color']
        
        # 获取画布尺寸
        canvas_width = self.canvas.winfo_width()
        canvas_height = self.canvas.winfo_height()
        
        if canvas_width < 100 or canvas_height < 100:
            # 如果画布太小，延迟显示
            self.canvas.after(100, lambda: self.display_poetry(poetry_data, current_index, highlight_color))
            return
        
        # 计算布局
        title_font = ('楷体', 24, 'bold')
        author_font = ('楷体', 16, 'italic')
        text_font = ('楷体', 20)
        pinyin_font = ('Arial', 14)
        
        # 显示标题
        title_y = 60
        title_item = self.canvas.create_text(
            canvas_width // 2, title_y,
            text=poetry_data['title'],
            font=title_font,
            fill=theme['text_color'],
            justify='center'
        )
        self.text_items.append(title_item)
        
        # 显示作者
        author_y = title_y + 40
        dynasty_text = f"【{poetry_data['dynasty']}】"
        author_text = f"{poetry_data['author']}"
        author_full_text = f"{dynasty_text} {author_text}"
        
        author_item = self.canvas.create_text(
            canvas_width // 2, author_y,
            text=author_full_text,
            font=author_font,
            fill=theme['pinyin_color'],
            justify='center'
        )
        self.text_items.append(author_item)
        
        # 显示诗句和拼音
        content_start_y = author_y + 60
        line_height = 50
        pinyin_offset = 25
        
        for i, (line, pinyin) in enumerate(zip(poetry_data['content'], poetry_data['pinyin'])):
            line_y = content_start_y + i * line_height
            
            # 显示诗句
            color = highlight_color if i == current_index else theme['text_color']
            line_item = self.canvas.create_text(
                canvas_width // 2, line_y,
                text=line,
                font=text_font,
                fill=color,
                justify='center'
            )
            self.text_items.append(line_item)
            
            # 显示拼音
            pinyin_y = line_y + pinyin_offset
            pinyin_item = self.canvas.create_text(
                canvas_width // 2, pinyin_y,
                text=pinyin,
                font=pinyin_font,
                fill=theme['pinyin_color'],
                justify='center'
            )
            self.pinyin_items.append(pinyin_item)
    
    def update_highlight(self, new_index, highlight_color=None):
        """更新高亮显示"""
        theme = self.style_manager.get_theme(self.current_theme)
        if highlight_color is None:
            highlight_color = theme['highlight_color']
        
        # 更新诗句颜色
        content_start_idx = 2  # 跳过标题和作者
        for i, item in enumerate(self.text_items[content_start_idx:]):
            if i == new_index:
                self.canvas.itemconfig(item, fill=highlight_color)
                # 添加放大效果
                current_font = self.canvas.itemcget(item, 'font')
                font_parts = current_font.split()
                if len(font_parts) >= 2:
                    font_name = font_parts[0]
                    font_size = int(font_parts[1])
                    new_font = (font_name, font_size + 2, 'bold')
                    self.canvas.itemconfig(item, font=new_font)
            else:
                self.canvas.itemconfig(item, fill=theme['text_color'])
                # 恢复原始字体
                current_font = self.canvas.itemcget(item, 'font')
                font_parts = current_font.split()
                if len(font_parts) >= 2 and 'bold' in current_font:
                    font_name = font_parts[0]
                    font_size = int(font_parts[1])
                    new_font = (font_name, font_size - 2)
                    self.canvas.itemconfig(item, font=new_font)
    
    def clear_display(self):
        """清除显示内容"""
        # 清除所有文本项
        for item in self.text_items + self.pinyin_items:
            self.canvas.delete(item)
        
        # 清除阴影项
        for item in self.shadow_items:
            self.canvas.delete(item)
        
        self.text_items.clear()
        self.pinyin_items.clear()
        self.shadow_items.clear()
    
    def set_background_image(self, image_path):
        """设置背景图片"""
        try:
            # 加载图片
            image = Image.open(image_path)
            
            # 调整图片大小以适应画布
            canvas_width = self.canvas.winfo_width()
            canvas_height = self.canvas.winfo_height()
            
            if canvas_width > 1 and canvas_height > 1:
                image = image.resize((canvas_width, canvas_height), Image.Resampling.LANCZOS)
                self.background_image = ImageTk.PhotoImage(image)
                
                # 创建背景图像
                if hasattr(self, 'bg_image_item'):
                    self.canvas.delete(self.bg_image_item)
                
                self.bg_image_item = self.canvas.create_image(
                    canvas_width // 2, canvas_height // 2,
                    image=self.background_image
                )
                
                # 将背景图像置于最底层
                self.canvas.tag_lower(self.bg_image_item, 'all')
                
                # 清除网格背景
                self.grid_bg.clear_grid()
                
        except Exception as e:
            print(f"设置背景图片失败: {e}")
    
    def remove_background_image(self):
        """移除背景图片"""
        if hasattr(self, 'bg_image_item'):
            self.canvas.delete(self.bg_image_item)
            delattr(self, 'bg_image_item')
        
        # 重新绘制网格背景
        self.grid_bg.draw_grid()